using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Web;
using System.Collections;
using System.Data;
using Maxima.Common;
using System.Collections.Generic;
using System.Text.RegularExpressions;
//using Microsoft.Security.Application;
//using Microsoft.Security.Application;

namespace Maxima.Common
{

    /// <summary>
    /// string extension methods
    /// </summary>

    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static string TrimAndReduce(this string str)
        {
            return ConvertWhitespacesToSingleSpaces(str).Trim();
        }

        public static string ConvertWhitespacesToSingleSpaces(this string value)
        {
            return Regex.Replace(value, @"\s+", " ");
        }


        public static string ToHex(this string strData)
        {
            string hex = string.Empty;
            foreach (char c in strData)
            {
                int tmp = c;
                hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }

        /// <summary>
        /// Hexes to string.
        /// </summary>
        /// <param name="str">The STR data.</param>
        /// <returns></returns>
        public static string HexToString(this string str)
        {
            string temp1 = string.Empty;
            string temp2 = string.Empty;

            while (str.Length > 0)
            {
                temp1 = System.Convert.ToChar(System.Convert.ToUInt32(str.Substring(0, 2), 16)).ToString();
                temp2 = temp2 + temp1;
                str = str.Substring(2, str.Length - 2);
            }

            return temp2;
        }

        public static byte[] ToBinary(this string str, int desiredLength)
        {
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] byteStream = new byte[(uint)desiredLength];
            encoder.GetBytes(str, 0, (str.Length <= desiredLength) ? str.Length : desiredLength, byteStream, 0);
            return byteStream;
        }

        public static byte[] ToBinary(this string str)
        {
            int desiredLength = str.Length;
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] byteStream = new byte[(uint)desiredLength];
            encoder.GetBytes(str, 0, (str.Length <= desiredLength) ? str.Length : desiredLength, byteStream, 0);
            return byteStream;
        }

        public static string ToBinary(this int nLength)
        {
            string str = Convert.ToString(nLength, 2);

            return str;
        }

        public static string BinaryToString(this string binary)
        {
            string str = string.Empty;
            foreach (char c in binary)
            {
                int tmp = c;
                str += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return str;
        }


        public static string BinaryToStringEx(this string binary)
        {
            var list = new List<Byte>();

            for (int i = 0; i < binary.Length; i += 8)
            {
                String t = binary.Substring(i, 8);

                list.Add(Convert.ToByte(t, 2));
            }

            return Encoding.ASCII.GetString(list.ToArray());

        }

        public static string ToMeta(this string strData)
        {
            string str = string.Empty;
            str = Convert.ToBase64String(ToBinary(strData, strData.Length));
            return str;
        }

        public static string ToMeta(this int nLength)
        {
            string str = string.Empty;
            str = Convert.ToChar(nLength).ToString();
            return str;
        }

        public static string ReplaceNonPrintables(this string str)
        {
            try
            {
                if (str.StartsWith("\0"))
                { str = str.Replace('\0', '?'); }

            }
            catch (Exception ex)
            {
                LogEx.Error("Error while replacing non printables", ex);
            }

            return str;
        }
    }

   
    public class Utility
    {
        public Utility() { }

        public static void VersionStamp()
        {
            LogEx.Info("One Potato Two Tomato v0.1 alpha");
            LogEx.Info("best instant messaging software");
            LogEx.Info( "(c) Copyright MaximaLabs 2014");
        }

        public static byte[] GetBytesFromBinaryString(string binary, int bitsPerByte)
        {
            List<byte> list = new List<byte>();
            for (int i = 0; i < binary.Length; i += bitsPerByte)
            {
                string t = binary.Substring(i, bitsPerByte);

                list.Add(Convert.ToByte(t, 2));
            }
            return list.ToArray();
        }





        private static string GetMetaLength(int nDataLength)
        {
            //Steps to calculate the meta length in characters
            //STEP 1: Get the div part. Divide data length by 256 - //int nPartDiv = nDataLength / 256;
            //STEP 2: Get the Modulus part. Take modulus of Data length by 256 - //int nPartMod = nDataLength % 256;
            //STEP 3: Convert into characters, concat and return. //Convert.ToChar(nPartDiv).ToString() + Convert.ToChar(nPartMod).ToString();

            string strLengthInChars = string.Empty;
            strLengthInChars = Convert.ToChar((nDataLength / 256)).ToString() + Convert.ToChar((nDataLength % 256)).ToString();
            List<string> lst = new List<string>();

            return strLengthInChars;
        }

        private const int DecimalRadix = 10;
        private const int MaxBit = 32;
        private static char[] _hexChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        private static int[] _hexValues = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
        /// <summary>
        /// Bases to decimal.
        /// </summary>
        /// <param name="completeHex">The complete hex.</param>
        /// <param name="radix">The radix.</param>
        /// <returns></returns>
        public static int BaseToDecimal(string completeHex, int radix)
        {
            int value = 0;
            int product = 1;
            for (int i = completeHex.Length - 1; i >= 0; i--, product = product * radix)
            {
                char hex = completeHex[i];
                int hexValue = -1;
                for (int j = 0; j < _hexChars.Length - 1; j++)
                {
                    if (_hexChars[j] == hex)
                    {
                        hexValue = _hexValues[j];
                        break;
                    }
                }
                value += (hexValue * product);
            }
            return value;
        }

        /// <summary>
        /// Decimals to base.
        /// </summary>
        /// <param name="decimalValue">The decimal value.</param>
        /// <param name="radix">The radix.</param>
        /// <returns></returns>
        public static string DecimalToBase(int decimalValue, int radix)
        {
            string completeHex = "";
            int[] remainders = new int[MaxBit];
            int maxBit = MaxBit;
            for (; decimalValue > 0; decimalValue = decimalValue / radix)
            {
                maxBit = maxBit - 1;
                remainders[maxBit] = decimalValue % radix;
            }
            for (int i = 0; i < remainders.Length; i++)
            {
                int value = remainders[i];
                if (value >= DecimalRadix)
                {
                    completeHex += _hexChars[value % DecimalRadix];
                }
                else
                {
                    completeHex += value;
                }
            }
            completeHex = completeHex.TrimStart(new char[] { '0' });
            return completeHex;

        }


        public static char[] Convert2CharArray(string str)
        {
            char[] ret = new char[str.Length];
            for (int i = 0; i < str.Length; i++) ret[i] = str[i];
            return ret;
        }

        public static string Convert2string(char[] charArray)
        {
            string ret = "";
            for (int i = 0; i < charArray.Length; i++) ret += charArray[i];
            return ret;
        }

        /// <summary>
        // 168-bit (three-key) 3DES (Triple-DES) encrypt a single 8-byte block (ECB mode)
        // plain-text should be 8-bytes, key should be 24 bytes.
        /// </summary>
        /// <see cref="http://www.chilkatsoft.com/p/p_330.asp"/>
        /// <param name="plainText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public byte[] To3DESEncryptOneBlock(byte[] plainText, byte[] key)
        {
            // Create a new 3DES key.
            System.Security.Cryptography.TripleDESCryptoServiceProvider des = new System.Security.Cryptography.TripleDESCryptoServiceProvider();

            // Set the KeySize = 192 for 168-bit DES encryption.
            // The msb of each byte is a parity bit, so the key length is actually 168 bits.
            des.KeySize = 192;
            des.Key = key;
            des.Mode = System.Security.Cryptography.CipherMode.ECB;
            des.Padding = System.Security.Cryptography.PaddingMode.None;

            System.Security.Cryptography.ICryptoTransform ic = des.CreateEncryptor();

            byte[] enc = ic.TransformFinalBlock(plainText, 0, 8);

            return enc;
        }

        static double m_nCounter = 0;
        public static string GetAutoNumber(int nLength)
        {
            string strRandom = string.Empty;
            try
            {
                strRandom = DateTime.Now.ToString("yyMMddHHmmssff") + m_nCounter.ToString().PadLeft(6, '0');
                if (m_nCounter > 999999)
                    m_nCounter = 0;
                m_nCounter++;

                if (nLength < strRandom.Length)
                    strRandom = strRandom.Substring(0, nLength);

            }
            catch (Exception ex)
            {
                LogEx.Error(ex);
            }
            return strRandom;
        }

        public static string Initials(string text, char seperator, string initialSeparator)
        {
            string temp = string.Empty;
            foreach (string str in text.Split(seperator))
            {
                temp += str[0] + initialSeparator;
            }
            return temp;
        }

        public static string ShowUpto(string text, int NoOfCharacters)
        {
            if (text.Length <= NoOfCharacters)
                return text;
            return text.Substring(0, NoOfCharacters - 3) + "...";
        }

        public static string ExtractFileName(string filenameandpath)
        {
            if (filenameandpath.Equals("")) return "";

            int pos = filenameandpath.LastIndexOf("\\") + 1;
            string filename = filenameandpath.Substring(pos);
            return filename;

        }

        public static string ConvertDateToString(DateTime date)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            return date.ToString();
        }

        public static bool DateIsValid(string date)
        {
            try
            {
                DateTime.ParseExact(date, "d/M/yyyy", null);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool NumberIsValid(string number)
        {
            try
            {
                Int32.Parse(number, NumberStyles.Any);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool AmountIsValid(string amount)
        {
            try
            {
                return Utility.AmountIsValid(amount, false);
            }
            catch
            {
                return false;
            }
        }

        public static bool PercentIsValid(string percent)
        {
            try
            {
                return (Decimal.Parse(percent) >= 0 && Decimal.Parse(percent) <= 100);
            }
            catch
            {
                return false;
            }
        }

        public static bool AmountIsValid(string amount, bool greaterThanZero)
        {
            try
            {
                if (greaterThanZero)
                    return (Decimal.Parse(amount, NumberStyles.Any) > 0);
                else
                    return (Decimal.Parse(amount, NumberStyles.Any) >= 0);
            }
            catch
            {
                return false;
            }
        }

        public static string ConvertDateToShortString(DateTime date)
        {

            if (!date.ToShortDateString().Equals("1/1/0001") && !date.ToShortDateString().Equals("01/01/0001"))
                return date.Day.ToString().PadLeft(2, '0') + "/" + date.Month.ToString().PadLeft(2, '0') + "/" + date.Year.ToString().PadLeft(2, '0');
            else
                return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static DateTime ConvertStringToDate(string date)
        {
            string[] dateParts = date.Split('/');
            int day = Convert.ToInt32(dateParts[0]);
            int month = Convert.ToInt32(dateParts[1]);
            int year = Convert.ToInt32(dateParts[2]);

            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            //date +=" 00:00:00";
            //return DateTime.Parse(date);

            //DateTime currentDate = DateTime.Parse(date);
            DateTime currentDate = new DateTime(year, month, day);
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            return currentDate;
        }

        public static string ConvertDateToLongString(DateTime date)
        {
            return date.ToString("dd/MM/yyyy hh:mm tt");
        }

        
        public static int GetDateDifference(DateTime a_StartDate, DateTime a_EndDate)
        {
            int i_DaysCount = 0;

            int m_YearsDiff = a_StartDate.Year - a_EndDate.Year;
            i_DaysCount = (a_EndDate.DayOfYear + (m_YearsDiff * 365)) - a_StartDate.DayOfYear;


            return i_DaysCount;
        }


        public static TimeSpan GetDateDifferenceInTimeSpan(DateTime a_StartDate, DateTime a_EndDate)
        {

            TimeSpan timeSpan = a_StartDate.Subtract(a_EndDate);

            return timeSpan;
        }


        /// <summary>
        /// This method will return Datetime object 
        /// </summary>
        /// <param name="a_DateTime"></param>
        /// <returns></returns>
        public static DateTime ConvertStringToDateTime(string dateTime)
        {
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            string[] dateTimeParts = dateTime.Split(' ');
            string[] dateParts = (dateTimeParts[0]).Split('/');
            string[] timeParts = (dateTimeParts[1]).Split(':');
            int day = Convert.ToInt32(dateParts[0]);
            int month = Convert.ToInt32(dateParts[1]);
            int year = Convert.ToInt32(dateParts[2]);
            int hour = Convert.ToInt32(timeParts[0]);
            int min = Convert.ToInt32(timeParts[1]);
            int sec = Convert.ToInt32(timeParts[2]);

            return new DateTime(year, month, day, hour, min, sec);

        }

        public static DateTime ConvertInternalStringToDate(string date)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            return DateTime.Parse(date);

        }

        public static DateTime ConvertDate(DateTime date)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

            return ConvertInternalStringToDate(ConvertDateToString(date));



        }

        public static DateTime ConvertTime(DateTime a_DateTime)
        {
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
            return ConvertInternalStringToDate(ConvertDateToString(a_DateTime));
        }

        /*public static  void SetCombo(DropDownList ctlListbox ,string valuetocompare)
        {
            for (int count=0; count< ctlListbox.Items.Count;count++)
            {
                if (ctlListbox.Items[count].Value.Equals(valuetocompare))
                {
                    ctlListbox.Items[count].Selected=true;
                    break;
                }
            }
        }
        public static  void SetCheckbox(CheckBoxList ctlListboxlist ,string valuetocompare)
        {
            for (int count=0; count< ctlListboxlist.Items.Count;count++)
            {
                if (ctlListboxlist.Items[count].Value.Equals(valuetocompare))
                {
                    ctlListboxlist.Items[count].Selected=true;
                    break;
                }
            }
        }
        */

        /// <summary>
        /// This method is used to apply quotes around a value being send as parameter
        /// </summary>
        /// <param name="stringWithoutQuote"></param>
        /// <returns>string value with quotes around it</returns>
        public static string ApplyDoubleQuotes(object stringWithoutQuote)
        {
            string temp = (String)stringWithoutQuote;
            if (!stringWithoutQuote.Equals(""))
            {
                temp = "'" + RectifyValues(temp) + "'";

            }
            return temp;
        }

        public static string RectifyValues(string stringWithSingleQuote, int maxLength)
        {
            if ((stringWithSingleQuote.Equals(string.Empty)) || (maxLength >= stringWithSingleQuote.Length))
                return RectifyValues(stringWithSingleQuote);

            return RectifyValues(stringWithSingleQuote.Remove(maxLength));
        }


        /// <summary>
        /// This method will rectify the string and add one more ' whereever it
        /// finds single ' .
        /// </summary>
        /// <param name="stringWithSingleQuote"></param>
        /// <returns></returns>
        public static string RectifyValues(string stringWithSingleQuote)
        {
            stringWithSingleQuote = stringWithSingleQuote.Trim();
            StringBuilder buffer = new StringBuilder(stringWithSingleQuote);
            buffer = buffer.Replace("\'", "\'\'");
            //buffer = buffer.Replace("\"","&quote;");

            return buffer.ToString();
        }

        /// <summary>
        /// This method will rectify the string found in DB as &#39 into single quote add one more ' whereever it
        /// finds single' .
        /// </summary>
        /// <param name="stringWithSingleQuote"></param>
        /// <returns></returns>
        public static string RectifyUniCodeFromDB(string stringWithSingleQuoteInDB)
        {
            StringBuilder buffer = new StringBuilder(stringWithSingleQuoteInDB);
            buffer = buffer.Replace("&#39", "'");
            buffer = buffer.Replace("&gt;", ">");
            buffer = buffer.Replace("&lt;", "<");
            buffer = buffer.Replace("&quote;", "\"");

            return buffer.ToString();
        }



        //		public static string RectifyValues(string stringWithSingleQuote)
        //		{
        //			StringBuilder buffer = new StringBuilder(stringWithSingleQuote);
        //			string ResultString = "";
        //			
        //			for (int i = 0;i<buffer.Length;i++)
        //			{
        //				
        //				if(buffer[i] == '\'')
        //				{
        //					ResultString += "&#39";
        //				}
        //				else if(buffer[i] == '\'')
        //				{
        //					ResultString += "&#39";
        //				}
        //				else 
        //				{
        //					ResultString += buffer[i];
        //				}
        //			}
        //			return ResultString;
        //		}

        public static string ReplaceEnter(string stringWithEnter)
        {

            StringBuilder buffer = new StringBuilder(stringWithEnter);
            string ResultString = "";

            for (int i = 0; i < buffer.Length; i++)
            {

                if (buffer[i] == '\n')
                {
                    ResultString += "<br>";
                }
                else
                {
                    ResultString += buffer[i];
                }
            }
            return ResultString;
        }

        public static DateTime getWeekBeginDate(DateTime a_DateTime)
        {
            DateTime WeekBeginDate = a_DateTime;
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

            int dayOfWeek = getDayOfWeek(a_DateTime.DayOfWeek);


            switch (dayOfWeek)
            {
                case 0: return WeekBeginDate.Subtract(TimeSpan.FromDays(0.0));
                case 1: return WeekBeginDate.Subtract(TimeSpan.FromDays(1.0));
                case 2: return WeekBeginDate.Subtract(TimeSpan.FromDays(2.0));
                case 3: return WeekBeginDate.Subtract(TimeSpan.FromDays(3.0));
                case 4: return WeekBeginDate.Subtract(TimeSpan.FromDays(4.0));
                case 5: return WeekBeginDate.Subtract(TimeSpan.FromDays(5.0));
                case 6: return WeekBeginDate.Subtract(TimeSpan.FromDays(6.0));
            }

            return a_DateTime;
        }

        public static int getDayOfWeek(DayOfWeek a_DayOfWeek)
        {
            switch (a_DayOfWeek)
            {
                case DayOfWeek.Monday: return 0;
                case DayOfWeek.Tuesday: return 1;
                case DayOfWeek.Wednesday: return 2;
                case DayOfWeek.Thursday: return 3;
                case DayOfWeek.Friday: return 4;
                case DayOfWeek.Saturday: return 5;
                case DayOfWeek.Sunday: return 6;

            }

            return 0;
        }

        private static string[] m_MonthsArray = new string[]{"January",
															"February",
															"March",
															"April",
															"May",
															"June",
															"July",
															"August",
															"September",
															"October",
															"November",
															"December"
															};

        public static string getMonthTitle(int a_MonthId)
        {
            if ((a_MonthId > 0) && (a_MonthId <= 12))
            {
                return m_MonthsArray[a_MonthId - 1];
            }
            return "";
        }

        public static bool isGreater(DateTime d1, DateTime d2)
        {
            if (d1 > d2)
                return true;
            return false;
        }

        public static bool isEqual(DateTime d1, DateTime d2)
        {
            if (d1.ToShortDateString().Equals(d2.ToShortDateString()))
                return true;
            return false;
        }

        public static string GetDateTimeSearchString(string fieldName, string op, string compareDate)
        {
            return GetDateTimeSearchString(fieldName, op, ConvertStringToDate(compareDate));
        }
        public static string GetDateTimeSearchString(string fieldName, string op, DateTime compareDate)
        {
            string searchCriteria = fieldName + op + ConvertDateTimeForSQL(compareDate);
            //searchCriteria += " Convert(datetime,'" + compareDate.ToString("dd MMM yyyy HH:mm:ss:fff") + "' , 113) ";
            return searchCriteria;
        }
        public static string ConvertDateTimeForSQL(DateTime date)
        {
            return " Convert(datetime,'" + date.ToString("dd MMM yyyy HH:mm:ss:fff") + "' , 113) ";
        }
        public static DateTime ToUpper(DateTime date)
        {
            return new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999);
        }
        public static DateTime ToLower(DateTime date)
        {
            return new DateTime(date.Year, date.Month, date.Day);
        }
        public static string ConvertDateTimeForSQL(DateTime date, bool max)
        {
            if (max)
                date = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999);
            else
                date = new DateTime(date.Year, date.Month, date.Day);
            return ConvertDateTimeForSQL(date);
        }

        public static int GetMonthDiff(DateTime d1, DateTime d2)
        {
            //d1-d2
            int totMonths;

            if (d1.Year == d2.Year && d1.Month == d2.Month)
            {
                return 0;
            }

            if (d1 > d2)
            {
                totMonths = 1;
                while (d2.AddMonths(totMonths) <= d1)
                {
                    totMonths++;
                }
            }
            else
            {
                totMonths = 1;
                while (d1.AddMonths(totMonths) <= d2)
                {
                    totMonths++;
                }
                totMonths = totMonths * -1;
            }

            return totMonths;
        }

        public static string GetDefValue(DataTable permissions, int moduleId, int serviceId)
        {
            DataRow[] dr = permissions.Select("ModuleId = " + moduleId.ToString() + " and ServiceId = " + serviceId.ToString());
            return dr[0]["DefOrder"].ToString();
        }

        // Added By: Shehzad Ahmed
        public static bool IsIntegral(string value)
        {
            string strValue = value.ToString();
            strValue = strValue.Substring(strValue.IndexOf('.') + 1);
            long decimalPart = Convert.ToInt64(strValue);
            if (decimalPart > 0)
                return false;
            else
                return true;

        }

        #region DataTable related Utils

        public static DataTable GetGroupedDataTable(DataTable sourceTable, string[] groupColNames, string[] aggregateColNames, string aggregateFuncName)
        {
            DataTable tempTable = new DataTable();
            DataTable resultTable = new DataTable();
            tempTable = sourceTable.Copy();

            resultTable = sourceTable.Clone();
            Hashtable ht = new Hashtable();
            string key = "";
            string filter = "";

            foreach (DataRow dr in tempTable.Rows)
            {
                filter = "";
                key = "";
                foreach (string s in groupColNames)
                {
                    if (tempTable.Columns[s].DataType == Type.GetType("System.DateTime"))
                    {
                        key += Convert.ToDateTime(dr[s]).Ticks.ToString();
                    }
                    else
                    {
                        key += dr[s].ToString() + "|";
                    }
                }
                if (!ht.ContainsKey(key))
                {
                    ht.Add(key, "");
                    DataRow currRow = resultTable.NewRow();
                    foreach (DataColumn dc in tempTable.Columns)
                    {
                        currRow[dc.ColumnName] = dr[dc.ColumnName];
                    }
                    filter = "";

                    int i = 0;
                    for (i = 0; i < groupColNames.Length; i++)
                    {
                        if (!filter.Equals(""))
                        {
                            filter += " AND ";
                        }
                        filter += groupColNames[i] + " = '" + dr[groupColNames[i]].ToString() + "'";
                    }

                    try
                    {
                        foreach (string aggregateCol in aggregateColNames)
                        {
                            currRow[aggregateCol] = Convert.ToDecimal(tempTable.Compute(aggregateFuncName + "(" + aggregateCol + ")", filter));

                        }

                        resultTable.Rows.Add(currRow);
                    }
                    catch
                    {

                    }
                }
            }

            return resultTable;
        }

        public static DataTable GetGroupedDataTable(DataTable sourceTable, string[] groupColNames, string aggregateColName, string aggregateFuncName)
        {
            DataTable tempTable = new DataTable();
            DataTable resultTable = new DataTable();
            tempTable = sourceTable.Copy();

            resultTable = sourceTable.Clone();
            Hashtable ht = new Hashtable();
            string key = "";
            string filter = "";
            foreach (DataRow dr in tempTable.Rows)
            {
                filter = "";
                key = "";
                foreach (string s in groupColNames)
                {
                    if (tempTable.Columns[s].DataType == Type.GetType("System.DateTime"))
                    {
                        key += Convert.ToDateTime(dr[s]).Ticks.ToString();
                    }
                    else
                    {
                        if (dr[s] != DBNull.Value) key += dr[s].ToString() + "|";
                    }
                }
                if (!ht.ContainsKey(key))
                {
                    ht.Add(key, "");
                    DataRow currRow = resultTable.NewRow();
                    foreach (DataColumn dc in tempTable.Columns)
                    {
                        currRow[dc.ColumnName] = dr[dc.ColumnName];
                    }
                    filter = "";

                    int i = 0;
                    for (i = 0; i < groupColNames.Length; i++)
                    {
                        if (!filter.Equals(""))
                        {
                            filter += " AND ";
                        }
                        filter += groupColNames[i] + " = '" + dr[groupColNames[i]].ToString() + "'";
                    }

                    try
                    {
                        currRow[aggregateColName] = Convert.ToDecimal(tempTable.Compute(aggregateFuncName + "(" + aggregateColName + ")", filter));
                        resultTable.Rows.Add(currRow);
                    }
                    catch
                    {

                    }
                }
            }

            return resultTable;
        }

        /// <summary>
        /// @Author   Karim Ismail
        /// @Dated  15/08/2007
        /// </summary>
        public static DataTable GetGroupedDataTableCount(DataTable sourceTable, string[] groupColNames)
        {
            DataTable tempTable = new DataTable();
            DataTable resultTable = new DataTable();
            tempTable = sourceTable.Copy();

            resultTable = sourceTable.Clone();
            resultTable.Columns.Add("Count", System.Type.GetType("System.Int32"));
            Hashtable ht = new Hashtable();
            string key = "";
            string filter = "";
            foreach (DataRow dr in tempTable.Rows)
            {
                filter = "";
                key = "";
                foreach (string s in groupColNames)
                {
                    if (tempTable.Columns[s].DataType == Type.GetType("System.DateTime"))
                    {
                        key += Convert.ToDateTime(dr[s]).Ticks.ToString();
                    }
                    else
                    {
                        if (dr[s] != DBNull.Value) key += dr[s].ToString() + "|";
                    }
                }
                if (!ht.ContainsKey(key))
                {
                    ht.Add(key, "");
                    DataRow currRow = resultTable.NewRow();
                    foreach (DataColumn dc in tempTable.Columns)
                    {
                        currRow[dc.ColumnName] = dr[dc.ColumnName];
                    }
                    filter = "";

                    int i = 0;
                    for (i = 0; i < groupColNames.Length; i++)
                    {
                        if (!filter.Equals(""))
                        {
                            filter += " AND ";
                        }
                        filter += groupColNames[i] + " = '" + dr[groupColNames[i]].ToString() + "'";
                    }

                    try
                    {
                        currRow["Count"] = Convert.ToInt32(tempTable.Compute("Count(" + groupColNames[0].ToString() + ")", filter));
                        resultTable.Rows.Add(currRow);
                    }
                    catch
                    {

                    }
                }
            }

            return resultTable;
        }

        /// <summary>
        /// @Author   Karim Ismail
        /// @Dated  15/08/2007
        /// </summary>
        public static DataTable GetGroupedDataTableCount(DataTable sourceTable, string[] groupColNames, string countColName)
        {
            DataTable tempTable = new DataTable();
            DataTable resultTable = new DataTable();
            tempTable = sourceTable.Copy();
            resultTable = sourceTable.Clone();
            Hashtable ht = new Hashtable();
            string key = "";
            string filter = "";
            foreach (DataRow dr in tempTable.Rows)
            {
                filter = "";
                key = "";
                foreach (string s in groupColNames)
                {
                    if (tempTable.Columns[s].DataType == Type.GetType("System.DateTime"))
                    {
                        key += Convert.ToDateTime(dr[s]).Ticks.ToString();
                    }
                    else
                    {
                        if (dr[s] != DBNull.Value) key += dr[s].ToString() + "|";
                    }
                }
                if (!ht.ContainsKey(key))
                {
                    ht.Add(key, "");
                    DataRow currRow = resultTable.NewRow();
                    foreach (DataColumn dc in tempTable.Columns)
                    {
                        currRow[dc.ColumnName] = dr[dc.ColumnName];
                    }
                    filter = "";

                    int i = 0;
                    for (i = 0; i < groupColNames.Length; i++)
                    {
                        if (!filter.Equals(""))
                        {
                            filter += " AND ";
                        }
                        filter += groupColNames[i] + " = '" + dr[groupColNames[i]].ToString() + "'";
                    }

                    try
                    {
                        currRow[countColName] = Convert.ToInt32(tempTable.Compute("Count(" + groupColNames[0].ToString() + ")", filter));
                        resultTable.Rows.Add(currRow);
                    }
                    catch
                    {

                    }
                }
            }
            return resultTable;
        }

        public static DataTable SelectDistinctDataTable(DataTable dtSourceTable, string[] targetColNames)
        {
            return SelectDistinctDataTable(dtSourceTable, targetColNames, null);
        }


        public static DataTable SelectDistinctDataTable(DataTable dtSourceTable, string[] targetColNames, string[] requiredColumns)
        {
            DataTable dtResultTable = new DataTable();

            if (requiredColumns != null && requiredColumns.Length > 0)
            {
                DataColumn dc = null;
                foreach (string colName in requiredColumns)
                {
                    dc = dtSourceTable.Columns[colName];
                    if (!dtResultTable.Columns.Contains(colName))
                        dtResultTable.Columns.Add(new DataColumn(colName, dc.DataType));
                }
            }
            else
                dtResultTable = dtSourceTable.Clone();

            if (dtSourceTable != null && dtSourceTable.Columns.Count > 0)
            {
                string key = "";
                Hashtable ht = new Hashtable();
                //DataTable dt = new DataTable();
                //dt = dtSourceTable.Clone();
                //dtResultTable = dtSourceTable.Clone();
                try
                {
                    foreach (DataRow dr in dtSourceTable.Rows)
                    {
                        key = "";
                        foreach (string str in targetColNames)
                            key += dr[str] + "|";

                        if (!ht.ContainsKey(key))
                        {
                            ht.Add(key, "");

                            DataRow drFinal = dtResultTable.NewRow();
                            foreach (DataColumn dc in dtResultTable.Columns)
                            {
                                drFinal[dc.ColumnName] = dr[dc.ColumnName];
                            }
                            bool isFound = false;
                            foreach (string str in targetColNames)
                            {
                                if (drFinal[str].Equals(DBNull.Value) || string.IsNullOrEmpty(drFinal[str].ToString()))
                                {
                                    isFound = true;
                                }
                            }
                            if (!isFound)
                                dtResultTable.Rows.Add(drFinal);
                        }
                    }
                    return dtResultTable;
                }
                catch
                {
                    return new DataTable();
                }
            }
            else
                return new DataTable();
        }
        /*
        public static DataTable SelectDistinctDataTable(DataTable dtSourceTable, string[] targetColNames)
        {
            DataTable dtResultTable = new DataTable();
            if (dtSourceTable != null && dtSourceTable.Columns.Count > 0)
            {
                string key = "";
                Hashtable ht = new Hashtable();
                DataTable dt = new DataTable();
                dt = dtSourceTable.Clone();
                dtResultTable = dtSourceTable.Clone();
                try
                {
                    foreach (DataRow dr in dtSourceTable.Rows)
                    {
                        key = "";
                        foreach (string str in targetColNames)
                            key += dr[str] + "|";

                        if (!ht.ContainsKey(key))
                        {
                            ht.Add(key, "");
                            dtResultTable.Rows.Add(dr.ItemArray);
                        }
                    }
                    return dtResultTable;
                }
                catch
                {
                    return new DataTable();
                }
            }
            else
                return new DataTable();
        }
        */
        public class DistictSearchCriteria
        {
            string _SearchCriteria;
            string _ColumnName;
            SqlDbType _ColumnType;


            public DistictSearchCriteria(string DateCriteria, string Column_Name)
            {
                _SearchCriteria = DateCriteria;
                _ColumnName = Column_Name;
                _ColumnType = SqlDbType.DateTime;
            }
            public string SerachCriteria
            {
                get
                {
                    return _SearchCriteria;
                }
            }
            public string ColumnName
            {
                get
                {
                    return _ColumnName;
                }
            }
            public SqlDbType ColumnType
            {
                get
                {
                    return _ColumnType;
                }
            }
        }

        public static class DateCriteria
        {
            public static string DATE = "DATE";
            public static string DATETIME = "DATETIME";
            public static string TIME = "TIME";
        }
        public static DataTable SelectDistict(DistictSearchCriteria[] Criteria, DataTable dtSource)
        {
            try
            {
                string _SearchKey;
                Hashtable Hash = new Hashtable();
                DataTable dtResult;
                if (Criteria != null & dtSource != null)
                {
                    dtResult = dtSource.Clone();

                    foreach (DataRow dr in dtSource.Rows)
                    {
                        _SearchKey = "";

                        foreach (DataColumn dc in dtSource.Columns)
                        {
                            foreach (DistictSearchCriteria ds in Criteria)
                            {
                                if (dc.ColumnName == ds.ColumnName)
                                {

                                    switch (ds.ColumnType)
                                    {
                                        case SqlDbType.DateTime:
                                            {
                                                if (ds.SerachCriteria == DateCriteria.DATE)
                                                {
                                                    _SearchKey += dr[ds.ColumnName].ToString().Substring(0, dr[ds.ColumnName].ToString().IndexOf(" "));
                                                    _SearchKey.Trim();
                                                    _SearchKey += "|";
                                                }
                                                else if (ds.SerachCriteria == DateCriteria.TIME)
                                                {
                                                    _SearchKey += dr[ds.ColumnName].ToString().Substring(dr[ds.ColumnName].ToString().IndexOf(" "), dr[ds.ColumnName].ToString().Length - 1);
                                                    _SearchKey.Trim();
                                                    _SearchKey += "|";
                                                }
                                                else if (ds.SerachCriteria == DateCriteria.DATETIME)
                                                {
                                                    _SearchKey += dr[ds.ColumnName].ToString() + "|";
                                                }
                                                break;
                                            }
                                        default:
                                            {
                                                _SearchKey += dr[ds.ColumnName].ToString() + "|";

                                                break;
                                            }
                                    }
                                }
                            }
                        }
                        if (!Hash.ContainsKey(_SearchKey))
                        {
                            Hash.Add(_SearchKey, "");
                            dtResult.Rows.Add(dr.ItemArray);

                        }


                    }
                    return dtResult;
                }
                else
                {
                    throw new Exception("Invalid Arguments");
                    //return null;
                }



            }
            catch
            {
                return null;
            }
        }

        public static DataSet Generate_DistinctDataTables(DataTable dtSource, string ColumnName)
        {
            DataSet dsResult;

            if (dtSource != null & ColumnName != null)
            {
                DistictSearchCriteria[] Criteria = new DistictSearchCriteria[1];
                Criteria[0] = new DistictSearchCriteria(DateCriteria.DATE, ColumnName);

                DataTable dtDistinct = SelectDistict(Criteria, dtSource);
                dsResult = new DataSet();

                foreach (DataRow dr in dtDistinct.Rows)
                {
                    DataTable dtTemp = dtSource.Clone();

                    foreach (DataRow drSource in dtSource.Rows)
                    {
                        if (drSource[ColumnName].ToString().Substring(0, drSource[ColumnName].ToString().IndexOf(" ")).Trim() == (dr[ColumnName].ToString().Substring(0, dr[ColumnName].ToString().IndexOf(" ")).Trim()))
                        {
                            dtTemp.Rows.Add(drSource.ItemArray);
                        }
                    }

                    dsResult.Tables.Add(dtTemp);

                }

                return dsResult;
            }
            else
            {
                return null;
            }

        }
        #endregion

        #region Rounding and Formating Functions
        public static string FormatAmount(string amount)
        {
            return FormatNumber(amount, Constants.COST_FORMAT_DIGIT);
        }
        public static string FormatAmount(string amount, int digit)
        {
            return FormatNumber(amount, digit);
        }
        public static string FormatPercentage(string percentage)
        {
            return FormatNumber(percentage, Constants.PERCENTAGE_FORMAT_DIGIT);
        }

        public static string FormatQuantity(string quantity)
        {
            return FormatNumber(quantity, Constants.QUANTITY_FORMAT_DIGIT);
        }
        public static string FormatNumber(decimal d, int digit)
        {
            return FormatNumber((object)d, digit);

        }
        public static string FormatNumber(double d, int digit)
        {
            return FormatNumber((object)d, digit);

        }
        public static string FormatNumber(int d, int digit)
        {
            return FormatNumber((object)d, digit);

        }
        public static string FormatNumber(string d, int digit)
        {
            if (string.IsNullOrEmpty(d))
                d = "0";
            return FormatNumber((object)decimal.Parse(d), digit);

        }
        private static string FormatNumber(object d, int digit)
        {
            return String.Format("{0:N" + digit.ToString() + "}", d);

        }

        public static double RoundNumber(double d, int digit)
        {
            return Math.Round(d, digit);
        }
        public static decimal RoundNumber(decimal d, int digit)
        {
            return Math.Round(d, digit);
        }
        #endregion


        public static string GetFieldValuesList(DataTable dt, string fieldName)
        {
            string List = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][fieldName] == DBNull.Value)
                    continue;
                List += dt.Rows[i][fieldName].ToString() + ",";
            }
            return List.TrimEnd(',');
        }
        public static string GetFieldValuesList(DataView dv, string fieldName)
        {
            string List = "";
            for (int i = 0; i < dv.Count; i++)
            {
                if (dv[i][fieldName] == DBNull.Value)
                    continue;
                List += dv[i][fieldName].ToString() + ", ";
            }
            return List.TrimEnd(',', ' ');
        }

        public static int getMaxNumberOfSameSuccessiveAlphabets(string text)
        {
            int finalNumSuccessive = 0;
            int numSuccessive = 0;

            char prevChar = '1';

            for (int i = 0; i < text.Length; i++)
            {
                if (!Char.IsLetter(text[i]))
                {
                    if (numSuccessive > finalNumSuccessive)
                    {
                        finalNumSuccessive = numSuccessive;
                    }
                    numSuccessive = 0;
                    continue;
                }

                if (numSuccessive == 0)
                {
                    prevChar = text[i];
                    numSuccessive++;
                }
                else if (text[i] == prevChar)
                {
                    numSuccessive++;
                }
                else
                {
                    if (numSuccessive > finalNumSuccessive)
                    {
                        finalNumSuccessive = numSuccessive;
                    }

                    prevChar = text[i];
                    numSuccessive = 1;
                }
            }

            if (numSuccessive > finalNumSuccessive)
            {
                finalNumSuccessive = numSuccessive;
            }

            return finalNumSuccessive;
        }

        public static int getMaxNumberOfSameSuccessiveDigits(string text)
        {
            int finalNumSuccessive = 0;
            int numSuccessive = 0;

            char prevChar = 'a';

            for (int i = 0; i < text.Length; i++)
            {
                if (!Char.IsDigit(text[i]))
                {
                    if (numSuccessive > finalNumSuccessive)
                    {
                        finalNumSuccessive = numSuccessive;
                    }
                    numSuccessive = 0;
                    continue;
                }

                if (numSuccessive == 0)
                {
                    prevChar = text[i];
                    numSuccessive++;
                }
                else if (text[i] == prevChar)
                {
                    numSuccessive++;
                }
                else
                {
                    if (numSuccessive > finalNumSuccessive)
                    {
                        finalNumSuccessive = numSuccessive;
                    }

                    prevChar = text[i];
                    numSuccessive = 1;
                }
            }

            if (numSuccessive > finalNumSuccessive)
            {
                finalNumSuccessive = numSuccessive;
            }

            return finalNumSuccessive;
        }

        public static int getAlphabetCount(string text)
        {
            int numAlphabets = 0;
            for (int i = 0; i < text.Length; i++)
            {
                if (Char.IsLetter(text[i]))
                    numAlphabets++;
            }
            return numAlphabets;
        }

        public static int getDigitCount(string text)
        {
            int numDigits = 0;
            for (int i = 0; i < text.Length; i++)
            {
                if (Char.IsDigit(text[i]))
                    numDigits++;
            }
            return numDigits;
        }

        public static int getMaxNumberOfSuccessiveAlphabets(string text)
        {
            int finalNumSuccessive = 0;
            int numSuccessive = 0;

            for (int i = 0; i < text.Length; i++)
            {
                if (Char.IsLetter(text[i]))
                {
                    numSuccessive++;
                }
                else
                {
                    if (numSuccessive > finalNumSuccessive)
                    {
                        finalNumSuccessive = numSuccessive;
                    }
                    numSuccessive = 0;
                }
            }

            return finalNumSuccessive;
        }

        public static string EncryptQueryString(string p)
        {
            return Convert.ToBase64String(ASCIIEncoding.Default.GetBytes(p));
        }

        public static string DecryptQueryString(string p)
        {
            return ASCIIEncoding.Default.GetString(Convert.FromBase64String(p));
        }

    }
}
